package com.freesun.shop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freesun.shop.entity.Prod;
import com.freesun.shop.entity.ProdComm;
import com.freesun.shop.entity.User;
import com.freesun.shop.service.ProdCommService;
import com.freesun.shop.service.ProdFavoriteService;
import com.freesun.shop.service.ProdService;
import com.freesun.shop.service.UserService;
import com.freesun.shop.vo.ProdCommVo;
import com.freesun.shop.vo.ProdVo;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProdController {

    @Reference(check = false)
    private ProdService prodService;

    @Reference(check = false)
    private ProdCommService prodCommService;
    @Reference(check = false)
    private ProdFavoriteService prodFavoriteService;

    @Autowired
    private UserService userService;

    @Autowired
    private MapperFacade mapperFacade;

    @ApiOperation("wx加载商品的详细信息")
    @GetMapping("/prod/prodInfo")
    public ResponseEntity<ProdVo> prodInfo(Long prodId) {
        Prod prod = prodService.getById(prodId);
        ProdVo prodVo = mapperFacade.map(prod, ProdVo.class);
        return ResponseEntity.ok(prodVo);
    }

    @ApiOperation("加载商品的评论数预览")
    @GetMapping("/prodComm/prodCommData")
    public ResponseEntity<ProdCommVo> prodCommVo(Long prodId) {
        ProdCommVo prodCommVo=  prodCommService.calCommentInfo(prodId);
        return ResponseEntity.ok(prodCommVo);
    }

    @ApiOperation("评论数据的分页查询")
    @GetMapping("/prodComm/prodCommPageByProd")
    public ResponseEntity<IPage<ProdComm>> pageComm(Page<ProdComm> page, ProdComm prodComm) {

        IPage<ProdComm> iPage =  prodCommService.findByPage(page, prodComm);
        List<ProdComm> records = iPage.getRecords();
        records.forEach(common -> {
            User user = userService.getById(common.getUserId());
            common.setPic(user.getPic());
            common.setNickName(user.getNickName());
        });
        return ResponseEntity.ok(iPage);
    }

    @ApiOperation("是否收藏")
    @GetMapping("/p/user/collection/isCollection")
    public ResponseEntity<Boolean> isComllection(Long prodId) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Boolean isOk=  prodFavoriteService.calUserIsComllection(prodId,user.getUserId());
        return ResponseEntity.ok(isOk);
    }

}